<script setup>
import { onMounted, ref, nextTick, watch } from "vue";
import { Search, Loading } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { en } from "element-plus/es/locales.mjs";

onMounted(() => {
  initData();
  loadBaiduMap();
});

// 初始化门店数据
const storeData = ref([]);
const searchQuery = ref("");
const initData = () => {
  axios.get("/storeDelivery/getAll").then((res) => {
    storeData.value = res.data.obj.map((store) => ({
      ...store,
      deliveryType: store.deliveryType || "fixed",
      minOrderAmount: store.minOrderAmount || 0,
      freeDeliveryThreshold: store.freeDeliveryThreshold || 0,
      fixedFee: store.fixedFee || 5,
      distanceFees: store.distanceFees
        ? JSON.parse(store.distanceFees)
        : [
            // 解析 JSON 字符串
            { distance: 3, fee: 5 },
            { distance: 5, fee: 8 },
            { distance: 10, fee: 12 },
          ],
    }));
  });
};

// 百度地图组件逻辑
const mapLoaded = ref(false);
const mapInstance = ref(null);
const activeStore = ref(null);
const loadBaiduMap = () => {
  if (window.BMap) {
    initMap();
    return;
  }

  // 添加全局变量定义
  if (typeof global === "undefined") {
    window.global = window;
  }

  window._BMapCallback = function () {
    mapLoaded.value = true;
    initMap();
  };

  const script = document.createElement("script");
  script.src = `https://api.map.baidu.com/api?v=3.0&ak=WNGj9FM3YGSzze0q1QPsfbka9YAfQxhR&callback=_BMapCallback`;
  script.onerror = () => {
    ElMessage.error("百度地图加载失败");
  };
  document.head.appendChild(script);
};

const initMap = () => {
  nextTick(() => {
    // 初始化地图实例
    // 在这里将mapInstance绑定到baidu-map上，后续所有的操作都在mapInstance上进行
    mapInstance.value = new BMap.Map("baidu-map");
    const point = new BMap.Point(116.404, 39.915);
    mapInstance.value.centerAndZoom(point, 5);
    mapInstance.value.enableScrollWheelZoom();
    mapInstance.value.addControl(new BMap.NavigationControl());
    if (activeStore.value) {
      centerToStore(activeStore.value);
    }
  });
  // 给一个延迟 地图加载完成之后才执行
  setTimeout(() => {
    allStores();
  }, 500);
};
// 进来页面就看到的大地图和所有店的标点方法
const allStores = () => {
  storeData.value.forEach((store) => {
    console.log(store);
    if (!mapInstance.value || !store.longitude || !store.latitude) return;
    const point = new BMap.Point(store.longitude, store.latitude);
    mapInstance.value.setZoom(5);
    // 添加新标记
    const marker = new BMap.Marker(point);
    // 添加点击事件，使得点击地图上的标记点可以显示信息窗口
    marker.addEventListener("click", function () {
      setActiveStore(store);
      searchQuery.value = store.storeName;
      // 开启信息窗口
    });
    mapInstance.value.addOverlay(marker);
    const label = new BMap.Label(store.storeName, {
      position: point,
      offset: new BMap.Size(10, -5),
    });
    mapInstance.value.addOverlay(label);
  });
};

// 点击大地图上的点，地图聚焦到店

// 点击左侧面板上的点，地图聚焦到店

const setActiveStore = (store) => {
  activeStore.value = store;
  if (mapInstance.value) {
    centerToStore(store);
  }
};

const centerToStore = (store) => {
  if (!mapInstance.value || !store.longitude || !store.latitude) return;

  const point = new BMap.Point(store.longitude, store.latitude);
  // 给一个延迟，让地图聚焦的时候，能确实接收到store.longitude和store.latitude
  setTimeout(() => {
    mapInstance.value.panTo(point);
  }, 100);
  mapInstance.value.setZoom(13);

  // 清除旧标记
  mapInstance.value.clearOverlays();

  // 添加新标记
  const marker = new BMap.Marker(point, {
    enableMassClear: false,
  });
  mapInstance.value.addOverlay(marker);

  const label = new BMap.Label(store.storeName, {
    position: point,
    offset: new BMap.Size(20, -10),
    enableMassClear: false,
  });

  mapInstance.value.addOverlay(label);
  if (store.deliveryType === "distance") {
    circleToStore(store);
  }
};

const circleToStore = (store) => {
  //画出以配送费阶梯距离为半径的同心圆
  if (store.distanceFees && store.distanceFees.length > 0) {
    store.distanceFees.forEach((fee) => {
      const point = new BMap.Point(store.longitude, store.latitude);
      setTimeout(() => {
        const circle = new BMap.Circle(point, fee.distance * 1000, {
          strokeColor: "#FF0000",
          strokeWeight: 2,
          strokeOpacity: 0.8,
          fillOpacity: 0.2,
          enableMassClear: true,
        });
        mapInstance.value.addOverlay(circle);
      }, 100);
    });
  }
};
const clearCircle = () => {
  setTimeout(() => {
    mapInstance.value.clearOverlays();
  }, 100);
};

const deliveryTypeOptions = [
  { label: "固定费用", value: "fixed" },
  { label: "按距离阶梯收费", value: "distance" },
];

// 阶梯收费方法
const handleSave = (store) => {
  const dataToSave = {
    ...store, // 展开所有store属性
    distanceFees: JSON.stringify(store.distanceFees), // 将数组转为JSON字符串
  };

  axios
    .post("/storeDelivery/update", dataToSave)
    .then((res) => {
      if (res.data) {
        ElMessage.success(`${store.storeName} 配送设置保存成功`);
      } else {
        ElMessage.error(res.data.message || "保存失败");
      }
    })
    .catch((err) => {
      ElMessage.error("请求失败");
      console.error(err);
    });
};

const addDistanceFee = (store) => {
  store.distanceFees.push({ distance: 0, fee: 0 });
};

const removeDistanceFee = (store, index) => {
  store.distanceFees.splice(index, 1);
};
</script>

<template>
  <div class="delivery-setting-container">
    <div class="header">
      <h2>外卖配送设置</h2>
      <el-input
        v-model="searchQuery"
        placeholder="搜索门店名称"
        style="width: 300px"
        clearable
        :prefix-icon="Search"
      />
    </div>

    <div class="content-wrapper">
      <!-- 左侧门店列表 -->
      <div class="store-list">
        <div
          v-for="store in storeData.filter((s) =>
            searchQuery ? s.storeName.includes(searchQuery) : true
          )"
          :key="store.id"
          class="store-card"
          :class="{ active: activeStore?.id === store.id }"
          @click="setActiveStore(store)"
        >
          <div class="store-header">
            <h3>{{ store.storeName }}</h3>
            <span class="store-city">{{ store.city }}</span>
          </div>

          <div class="store-body">
            <el-form label-width="120px">
              <el-form-item label="起送价(元)">
                <el-input-number
                  v-model="store.minOrderAmount"
                  :min="0"
                  :step="1"
                  controls-position="right"
                />
              </el-form-item>

              <el-form-item label="满多少免配送费">
                <el-input-number
                  v-model="store.freeDeliveryThreshold"
                  :min="0"
                  :step="1"
                  controls-position="right"
                />
              </el-form-item>

              <el-form-item label="配送费类型">
                <el-radio-group v-model="store.deliveryType">
                  <el-radio
                    v-for="item in deliveryTypeOptions"
                    :key="item.value"
                    :label="item.value"
                    @click="
                      console.log(item.value);
                      item.value === 'fixed'
                        ? clearCircle()
                        : circleToStore(store);
                    "
                  >
                    {{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item
                v-if="store.deliveryType === 'fixed'"
                label="固定配送费"
              >
                <el-input-number
                  v-model="store.fixedFee"
                  :min="0"
                  :step="1"
                  controls-position="right"
                />
              </el-form-item>

              <template v-if="store.deliveryType === 'distance'">
                <el-form-item label="距离阶梯费用">
                  <div
                    v-for="(fee, index) in store.distanceFees"
                    :key="index"
                    class="distance-fee-item"
                  >
                    <el-input-number
                      v-model="fee.distance"
                      :min="0"
                      :step="1"
                      controls-position="right"
                      placeholder="距离(km)"
                      style="width: 80px"
                    />
                    <span class="fee-label">公里内收费</span>
                    <el-input-number
                      v-model="fee.fee"
                      :min="0"
                      :step="1"
                      controls-position="right"
                      placeholder="费用(元)"
                      style="width: 80px"
                    />
                    <el-button
                      type="danger"
                      size="small"
                      @click.stop="removeDistanceFee(store, index)"
                    >
                      删除
                    </el-button>
                  </div>
                  <el-button
                    type="primary"
                    size="small"
                    @click.stop="addDistanceFee(store)"
                  >
                    添加阶梯
                  </el-button>
                </el-form-item>
              </template>
            </el-form>
          </div>

          <div class="store-footer">
            <el-button type="primary" @click.stop="handleSave(store)">
              保存设置
            </el-button>
          </div>
        </div>
      </div>

      <!-- 右侧地图 -->
      <div class="map-container">
        <div v-if="!mapLoaded" class="map-loading">
          <el-icon class="is-loading" :size="30">
            <Loading />
          </el-icon>
          <span>地图加载中...</span>
        </div>
        <div v-else id="baidu-map" class="baidu-map"></div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.delivery-setting-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 10px;
    h2 {
      margin: 0;
      color: #333;
    }
  }

  .content-wrapper {
    display: flex;
    flex: 1;
    gap: 20px;
    overflow: hidden;

    .store-list {
      width: 450px;
      overflow-y: auto;
      padding-right: 10px;

      .store-card {
        background-color: #fff;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 15px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
        }

        &.active {
          border-left: 4px solid #409eff;
          background-color: #f0f7ff;
        }

        .store-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
          padding-bottom: 10px;
          border-bottom: 1px solid #eee;

          h3 {
            margin: 0;
            font-size: 16px;
            color: #333;
          }

          .store-city {
            background-color: #f0f0f0;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 12px;
            color: #666;
          }
        }

        .store-body {
          .distance-fee-item {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;

            .fee-label {
              white-space: nowrap;
              color: #666;
            }
          }
        }

        .store-footer {
          display: flex;
          justify-content: flex-end;
          margin-top: 15px;
          padding-top: 10px;
          border-top: 1px solid #eee;
        }
      }
    }

    .map-container {
      flex: 1;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      position: relative;
      overflow: hidden;

      .map-loading {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: rgba(255, 255, 255, 0.8);
        z-index: 10;

        span {
          margin-top: 10px;
          color: #666;
        }
      }

      .baidu-map {
        width: 100%;
        height: 100%;
      }
    }
  }
}

/* 滚动条样式 */
.store-list::-webkit-scrollbar {
  width: 6px;
}

.store-list::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.store-list::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
</style>
